# 生产环境部署脚本
param(
    [switch]$Build,      # 重新构建镜像
    [switch]$Stop,       # 停止服务
    [switch]$Logs,       # 查看日志
    [switch]$Status,     # 查看状态
    [string]$Service,    # 指定服务名
    [switch]$Help        # 显示帮助
)

function Show-Help {
    Write-Host "=== 在线学习平台 - 生产环境部署脚本 ===" -ForegroundColor Green
    Write-Host ""
    Write-Host "用法:" -ForegroundColor Cyan
    Write-Host "  .\deploy.ps1                启动所有服务"
    Write-Host "  .\deploy.ps1 -Build         重新构建并启动"
    Write-Host "  .\deploy.ps1 -Stop          停止所有服务"
    Write-Host "  .\deploy.ps1 -Logs          查看所有日志"
    Write-Host "  .\deploy.ps1 -Logs -Service backend  查看指定服务日志"
    Write-Host "  .\deploy.ps1 -Status        查看服务状态"
    Write-Host "  .\deploy.ps1 -Help          显示此帮助"
    Write-Host ""
    Write-Host "环境变量 (.env 文件):" -ForegroundColor Yellow
    Write-Host "  DB_PASSWORD=your_db_password"
    Write-Host "  JWT_SECRET=your_jwt_secret"
    Write-Host "  OPENAI_API_KEY=your_openai_key"
    Write-Host ""
}

function Test-DockerRequirements {
    if (!(Get-Command "docker" -ErrorAction SilentlyContinue)) {
        Write-Host "❌ Docker 未安装" -ForegroundColor Red
        return $false
    }
    
    if (!(Get-Command "docker-compose" -ErrorAction SilentlyContinue)) {
        Write-Host "❌ Docker Compose 未安装" -ForegroundColor Red
        return $false
    }
    
    # 检查Docker是否运行
    try {
        docker ps | Out-Null
        Write-Host "✓ Docker 环境检查通过" -ForegroundColor Green
        return $true
    } catch {
        Write-Host "❌ Docker 服务未运行" -ForegroundColor Red
        return $false
    }
}

function Initialize-Environment {
    # 检查并创建 .env 文件
    if (!(Test-Path ".env")) {
        Write-Host "创建 .env 文件..." -ForegroundColor Yellow
        Copy-Item "env.example" ".env"
        Write-Host "⚠️  请编辑 .env 文件设置生产环境配置" -ForegroundColor Yellow
        return $false
    }
    return $true
}

function Start-Services {
    param([bool]$rebuild = $false)
    
    Write-Host "=== 启动在线学习平台 ===" -ForegroundColor Green
    
    if ($rebuild) {
        Write-Host "重新构建镜像..." -ForegroundColor Yellow
        docker-compose build --no-cache
    }
    
    Write-Host "启动服务..." -ForegroundColor Yellow
    docker-compose up -d
    
    Write-Host "等待服务启动..." -ForegroundColor Yellow
    Start-Sleep 10
    
    Show-ServiceStatus
    Show-AccessUrls
}

function Stop-Services {
    Write-Host "停止所有服务..." -ForegroundColor Yellow
    docker-compose down
    Write-Host "✓ 所有服务已停止" -ForegroundColor Green
}

function Show-ServiceStatus {
    Write-Host "`n=== 服务状态 ===" -ForegroundColor Cyan
    docker-compose ps
}

function Show-Logs {
    param([string]$serviceName = "")
    
    if ($serviceName) {
        Write-Host "查看 $serviceName 服务日志..." -ForegroundColor Yellow
        docker-compose logs -f $serviceName
    } else {
        Write-Host "查看所有服务日志..." -ForegroundColor Yellow
        docker-compose logs -f
    }
}

function Test-Services {
    $services = @(
        @{ Name = "前端"; Url = "http://localhost" },
        @{ Name = "后端健康检查"; Url = "http://localhost/api/v1/health" },
        @{ Name = "AI服务健康检查"; Url = "http://localhost/ai/health" }
    )
    
    Write-Host "`n=== 服务健康检查 ===" -ForegroundColor Cyan
    
    foreach ($service in $services) {
        try {
            $response = Invoke-WebRequest -Uri $service.Url -TimeoutSec 10 -UseBasicParsing
            if ($response.StatusCode -eq 200) {
                Write-Host "✓ $($service.Name) - 正常" -ForegroundColor Green
            } else {
                Write-Host "⚠️  $($service.Name) - 异常 (状态码: $($response.StatusCode))" -ForegroundColor Yellow
            }
        } catch {
            Write-Host "❌ $($service.Name) - 无法访问" -ForegroundColor Red
        }
    }
}

function Show-AccessUrls {
    Write-Host "`n=== 访问地址 ===" -ForegroundColor Cyan
    Write-Host "🌐 前端应用: http://localhost" -ForegroundColor White
    Write-Host "🔧 后端API: http://localhost/api/v1/health" -ForegroundColor White
    Write-Host "🤖 AI服务: http://localhost/ai/health" -ForegroundColor White
    Write-Host "📊 数据库: localhost:3306 (learning/learning123)" -ForegroundColor White
    Write-Host ""
    Write-Host "💡 提示: 首次启动可能需要几分钟时间进行数据库初始化" -ForegroundColor Yellow
}

function Show-MaintenanceCommands {
    Write-Host "`n=== 维护命令 ===" -ForegroundColor Cyan
    Write-Host "查看容器状态: docker-compose ps"
    Write-Host "查看日志: docker-compose logs -f [service_name]"
    Write-Host "重启服务: docker-compose restart [service_name]"
    Write-Host "更新镜像: docker-compose pull && docker-compose up -d"
    Write-Host "清理: docker-compose down -v (⚠️ 会删除数据)"
    Write-Host ""
}

# 主逻辑
if ($Help) {
    Show-Help
    exit
}

if (!(Test-DockerRequirements)) {
    Write-Host "请先安装并启动 Docker" -ForegroundColor Red
    exit 1
}

if ($Stop) {
    Stop-Services
    exit
}

if ($Status) {
    Show-ServiceStatus
    Test-Services
    exit
}

if ($Logs) {
    Show-Logs -serviceName $Service
    exit
}

# 初始化环境
if (!(Initialize-Environment)) {
    exit 1
}

# 默认启动服务
Start-Services -rebuild $Build

# 等待一段时间后进行健康检查
Write-Host "等待服务完全启动..." -ForegroundColor Yellow
Start-Sleep 30

Test-Services
Show-MaintenanceCommands


